package zhklappoint.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import zhklappoint.dao.ApiTokenMapper;
import zhklappoint.entity.TokenEntity;
import zhklappoint.enums.ENUM_ISDELETE;

@Service
public class TokenService {
    @Autowired
    private ApiTokenMapper tokenDao;
    /**
     * 30天过期
     */
    private final static Long EXPIRE = 3600 * 24 * 30L;

    public TokenEntity findByUserIdAndIsdelete(String userId) {
        return tokenDao.findByUserIdAndIsdelete(userId, ENUM_ISDELETE.NOT_DELETED.value);
    }

    public TokenEntity findByTokenAndIsdelete(String token) {
        return tokenDao.findByTokenAndIsdelete(token,ENUM_ISDELETE.NOT_DELETED.value);
    }

    public void save(TokenEntity token) {
        tokenDao.save(token);
    }

    public Map<String, Object> createToken(String userId,Integer type) {
        //生成一个token
        String token=UUID.randomUUID().toString().replaceAll("-","");
        if(!ObjectUtils.isEmpty(type)&&type==1) {//投票系统的token
        	token="vote"+token;
        }else if(!ObjectUtils.isEmpty(type)&&type==2) {//H5的token
        	token="H5"+token;
        }
        //当前时间
        Date now = new Date();

        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        TokenEntity tokenEntity = findByUserIdAndIsdelete(userId);
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //保存token
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
        }
        save(tokenEntity);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", EXPIRE);

        return map;
    }
}
